package com.share.device.controller;

/**
 * @version 1.0
 * @author: CY_Guo
 * @date: 2025/5/19 17:31
 * @Descript TODO 请概括该类
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.share.common.core.domain.R;
import com.share.device.domain.RegionLocation;
import com.share.device.service.IRegionLocationService;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Tag(name = "地区定位接口管理")
@RestController
@RequestMapping("/region/re")
@Slf4j
public class RegionLocationController {

    @Value("${tencent.map.key}")
    private String mapKey; // 读取share-device-dev.yml配置文件中的tencent.map.key腾讯地图key

    @Autowired
    private IRegionLocationService regionLocationService;

    @GetMapping("/location")  // 这个路径已经正确
    public R<RegionLocation> getLocation(@RequestParam("districtCode") String districtCode) {
        try {
            log.info("获取地区经纬度，地区编码：{}", districtCode);

            // 先从数据库查询
            RegionLocation location = regionLocationService.getLocationByDistrictCode(districtCode);
            if (location != null) {
                log.info("从数据库获取到地区经纬度：{}", location);
                return R.ok(location);
            }

            // 如果数据库中没有，则调用高德地图API
            /*String url = String.format(
                    "https://restapi.amap.com/v3/geocode/geo?key=%s&address=%s",
                    mapKey,
                    districtCode
            );*/
            // 如果数据库中没有，则调用腾讯地图API
            String url = String.format(
                    "https://apis.map.qq.com/ws/geocoder/v1/?address=%s&key=%s",
                    districtCode,
                    mapKey
            );

            log.info("调用腾讯地图API，URL：{}", url);

            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet request = new HttpGet(url);
                try (CloseableHttpResponse response = client.execute(request)) {
                    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                    log.info("腾讯地图API响应：{}", result);

                    JSONObject jsonResponse = JSON.parseObject(result);

                    if (jsonResponse.getInteger("status") == 0) {
                        JSONObject resultObj = jsonResponse.getJSONObject("result");
                        JSONObject locationObj = resultObj.getJSONObject("location");

                        location = new RegionLocation();
                        location.setDistrictCode(districtCode);
                        location.setLatitude(locationObj.getDouble("lat"));
                        location.setLongitude(locationObj.getDouble("lng"));
                        location.setFormattedAddress(resultObj.getString("formatted_addresses"));

                        // 保存到数据库
                        regionLocationService.saveLocation(location);

                        log.info("成功获取并保存地区经纬度：{}", location);
                        return R.ok(location);
                    }
                }
            }

            log.warn("获取地区经纬度失败，使用默认值");
            return R.ok(getDefaultLocation());

        } catch (Exception e) {
            log.error("获取地区经纬度异常", e);
            return R.ok(getDefaultLocation());
        }
    }

    private RegionLocation getDefaultLocation() {
        RegionLocation location = new RegionLocation();
        location.setLatitude(39.908823);
        location.setLongitude(116.397470);
        location.setFormattedAddress("北京市东城区天安门");
        return location;
    }

}
